import { createSlice, PayloadAction } from '@reduxjs/toolkit';

// 从localStorage中获取初始token
const getInitialToken = (): string => {
  try {
    return localStorage.getItem('accessToken') || '';
  } catch {
    return '';
  }
};

// 从localStorage中获取初始refresh token
const getInitialRefreshToken = (): string => {
  try {
    return localStorage.getItem('refreshToken') || '';
  } catch {
    return '';
  }
};

interface TokenState {
  accessToken: string;
  refreshToken: string;
}

const initialState: TokenState = {
  accessToken: getInitialToken(),
  refreshToken: getInitialRefreshToken(),
};

const tokenSlice = createSlice({
  name: '@@app/token',
  initialState,
  reducers: {
    setTokens: (state, action: PayloadAction<{ accessToken: string; refreshToken: string }>) => {
      state.accessToken = action.payload.accessToken;
      state.refreshToken = action.payload.refreshToken;
      try {
        localStorage.setItem('accessToken', action.payload.accessToken);
        localStorage.setItem('refreshToken', action.payload.refreshToken);
      } catch (error) {
        console.error('Failed to save tokens to localStorage:', error);
      }
    },
    setAccessToken: (state, action: PayloadAction<string>) => {
      state.accessToken = action.payload;
      try {
        localStorage.setItem('accessToken', action.payload);
      } catch (error) {
        console.error('Failed to save token to localStorage:', error);
      }
    },
    setRefreshToken: (state, action: PayloadAction<string>) => {
      state.refreshToken = action.payload;
      try {
        localStorage.setItem('refreshToken', action.payload);
      } catch (error) {
        console.error('Failed to save refresh token to localStorage:', error);
      }
    },
    clearTokens: (state) => {
      state.accessToken = '';
      state.refreshToken = '';
      try {
        localStorage.removeItem('accessToken');
        localStorage.removeItem('refreshToken');
      } catch (error) {
        console.error('Failed to remove tokens from localStorage:', error);
      }
    },
    clearAccessToken: (state) => {
      state.accessToken = '';
      try {
        localStorage.removeItem('accessToken');
      } catch (error) {
        console.error('Failed to remove token from localStorage:', error);
      }
    },
  },
});

export const { setTokens, setAccessToken, setRefreshToken, clearTokens, clearAccessToken } = tokenSlice.actions;

export default tokenSlice.reducer;